<template>
  <el-dialog
    v-model="dialogVisible"
    title="常用收款人管理"
    width="600px"
    :close-on-click-modal="false"
  >
    <div class="payee-manage">
      <!-- 操作栏 -->
      <div class="actions-bar">
        <el-button type="primary" @click="showAddDialog">
          <el-icon><Plus /></el-icon>
          添加收款人
        </el-button>
      </div>

      <!-- 收款人列表 -->
      <div class="payee-list">
        <div v-if="payeeList.length === 0" class="empty-state">
          <el-empty description="暂无常用收款人">
            <el-button type="primary" @click="showAddDialog">添加收款人</el-button>
          </el-empty>
        </div>
        
        <div v-else>
          <div
            v-for="payee in payeeList"
            :key="payee.id"
            class="payee-item"
            @click="selectPayee(payee)"
          >
            <div class="payee-info">
              <div class="payee-name">{{ payee.name }}</div>
              <div class="payee-card">{{ formatCardNumber(payee.cardId) }}</div>
              <div class="payee-bank">{{ payee.bankName || '中国银行' }}</div>
            </div>
            <div class="payee-actions">
              <el-button size="small" type="text" @click.stop="editPayee(payee)">
                编辑
              </el-button>
              <el-button size="small" type="text" @click.stop="deletePayee(payee)" class="danger">
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑收款人对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      :title="editingPayee ? '编辑收款人' : '添加收款人'"
      width="400px"
      append-to-body
    >
      <el-form
        ref="payeeFormRef"
        :model="payeeForm"
        :rules="payeeRules"
        label-width="100px"
      >
        <el-form-item label="收款人姓名" prop="name">
          <el-input
            v-model="payeeForm.name"
            placeholder="请输入收款人姓名"
            maxlength="20"
          />
        </el-form-item>

        <el-form-item label="银行卡号" prop="cardId">
          <el-input
            v-model="payeeForm.cardId"
            placeholder="请输入银行卡号"
            maxlength="16"
            @blur="verifyCard"
          />
        </el-form-item>

        <el-form-item label="开户银行" prop="bankName">
          <el-input
            v-model="payeeForm.bankName"
            placeholder="请输入开户银行"
            maxlength="50"
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="payeeForm.remark"
            placeholder="请输入备注信息（可选）"
            maxlength="100"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="saveLoading" @click="savePayee">
            {{ editingPayee ? '保存' : '添加' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

export default {
  name: 'PayeeManageDialog',
  components: {
    Plus
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:visible', 'select'],
  setup(props, { emit }) {
    // 数据
    const payeeList = ref([])
    const loading = ref(false)
    const saveLoading = ref(false)
    
    // 对话框状态
    const addDialogVisible = ref(false)
    const editingPayee = ref(null)
    
    // 表单
    const payeeFormRef = ref()
    const payeeForm = reactive({
      name: '',
      cardId: '',
      bankName: '中国银行',
      remark: ''
    })

    // 计算属性
    const dialogVisible = computed({
      get: () => props.visible,
      set: (value) => emit('update:visible', value)
    })

    // 表单验证规则
    const payeeRules = {
      name: [
        { required: true, message: '请输入收款人姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度在2-20个字符', trigger: 'blur' }
      ],
      cardId: [
        { required: true, message: '请输入银行卡号', trigger: 'blur' },
        { 
          pattern: /^10103576\d{8}$/, 
          message: '请输入正确的银行卡号格式', 
          trigger: 'blur' 
        }
      ],
      bankName: [
        { required: true, message: '请输入开户银行', trigger: 'blur' }
      ]
    }

    // 获取收款人列表
    const fetchPayeeList = () => {
      try {
        // 从localStorage获取收款人列表
        const savedPayees = localStorage.getItem('payeeList')
        if (savedPayees) {
          payeeList.value = JSON.parse(savedPayees)
        } else {
          payeeList.value = []
        }
      } catch (error) {
        console.error('获取收款人列表失败:', error)
        payeeList.value = []
      }
    }

    // 保存收款人列表到localStorage
    const savePayeeList = () => {
      try {
        localStorage.setItem('payeeList', JSON.stringify(payeeList.value))
      } catch (error) {
        console.error('保存收款人列表失败:', error)
      }
    }

    // 显示添加对话框
    const showAddDialog = () => {
      editingPayee.value = null
      resetForm()
      addDialogVisible.value = true
    }

    // 编辑收款人
    const editPayee = (payee) => {
      editingPayee.value = payee
      Object.assign(payeeForm, {
        name: payee.name,
        cardId: payee.cardId,
        bankName: payee.bankName || '中国银行',
        remark: payee.remark || ''
      })
      addDialogVisible.value = true
    }

    // 删除收款人
    const deletePayee = async (payee) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除收款人"${payee.name}"吗？`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const index = payeeList.value.findIndex(p => p.id === payee.id)
        if (index > -1) {
          payeeList.value.splice(index, 1)
          savePayeeList()
          ElMessage.success('删除成功')
        }
      } catch (error) {
        // 用户取消删除
      }
    }

    // 选择收款人
    const selectPayee = (payee) => {
      emit('select', payee)
      dialogVisible.value = false
    }

    // 验证银行卡
    const verifyCard = async () => {
      if (!payeeForm.cardId || !/^10103576\d{8}$/.test(payeeForm.cardId)) {
        return
      }

      // 这里可以调用API验证银行卡是否存在
      // 暂时使用简单的模拟验证
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // 检查是否已存在
        const exists = payeeList.value.some(p => 
          p.cardId === payeeForm.cardId && 
          (!editingPayee.value || p.id !== editingPayee.value.id)
        )
        
        if (exists) {
          ElMessage.warning('该银行卡号已存在于收款人列表中')
          return
        }

        ElMessage.success('银行卡验证成功')
      } catch (error) {
        ElMessage.error('银行卡验证失败')
      }
    }

    // 保存收款人
    const savePayee = async () => {
      if (!payeeFormRef.value) return

      try {
        await payeeFormRef.value.validate()
        saveLoading.value = true

        // 检查是否已存在相同银行卡号
        const exists = payeeList.value.some(p => 
          p.cardId === payeeForm.cardId && 
          (!editingPayee.value || p.id !== editingPayee.value.id)
        )
        
        if (exists) {
          ElMessage.warning('该银行卡号已存在于收款人列表中')
          return
        }

        if (editingPayee.value) {
          // 编辑
          const index = payeeList.value.findIndex(p => p.id === editingPayee.value.id)
          if (index > -1) {
            payeeList.value[index] = {
              ...editingPayee.value,
              ...payeeForm,
              updateTime: new Date().toISOString()
            }
          }
          ElMessage.success('编辑成功')
        } else {
          // 添加
          const newPayee = {
            id: Date.now().toString(),
            ...payeeForm,
            createTime: new Date().toISOString()
          }
          payeeList.value.unshift(newPayee)
          ElMessage.success('添加成功')
        }

        savePayeeList()
        addDialogVisible.value = false
        resetForm()
      } catch (error) {
        console.error('保存收款人失败:', error)
      } finally {
        saveLoading.value = false
      }
    }

    // 重置表单
    const resetForm = () => {
      Object.assign(payeeForm, {
        name: '',
        cardId: '',
        bankName: '中国银行',
        remark: ''
      })
      if (payeeFormRef.value) {
        payeeFormRef.value.resetFields()
      }
    }

    // 格式化银行卡号
    const formatCardNumber = (cardNumber) => {
      if (!cardNumber) return ''
      return cardNumber.replace(/(\d{4})(?=\d)/g, '$1 ')
    }

    // 监听对话框显示状态
    watch(() => props.visible, (visible) => {
      if (visible) {
        fetchPayeeList()
      }
    })

    onMounted(() => {
      fetchPayeeList()
    })

    return {
      payeeList,
      loading,
      saveLoading,
      dialogVisible,
      addDialogVisible,
      editingPayee,
      payeeFormRef,
      payeeForm,
      payeeRules,
      showAddDialog,
      editPayee,
      deletePayee,
      selectPayee,
      verifyCard,
      savePayee,
      resetForm,
      formatCardNumber
    }
  }
}
</script>

<style lang="scss" scoped>
.payee-manage {
  .actions-bar {
    margin-bottom: 16px;
    text-align: right;
  }

  .payee-list {
    .empty-state {
      text-align: center;
      padding: 40px 0;
    }

    .payee-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      margin-bottom: 12px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        border-color: #409eff;
        background-color: #f0f9ff;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
      }

      .payee-info {
        flex: 1;

        .payee-name {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
          margin-bottom: 4px;
        }

        .payee-card {
          font-size: 14px;
          color: #606266;
          margin-bottom: 2px;
          font-family: 'Courier New', monospace;
        }

        .payee-bank {
          font-size: 12px;
          color: #909399;
        }
      }

      .payee-actions {
        display: flex;
        gap: 8px;

        .el-button {
          padding: 4px 8px;
          
          &.danger {
            color: #f56c6c;
            
            &:hover {
              color: #f56c6c;
              background-color: #fef0f0;
            }
          }
        }
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style> 